﻿using System;
using System.Collections.Generic;
using System.IO;
using System.IO.Compression;
using System.Reflection;
using System.Windows;
using System.Xml.Linq;

namespace 灵溪工具箱
{
    // 灵溪工具箱的插件管理窗口类
    public partial class PluginManagerWindow : Window
    {
        private const string PLUGIN_DIRECTORY = "Plugins";
        private const string LOG_DIRECTORY = "log";

        // 存储插件信息的列表
        private List<PluginInfo> plugins = new List<PluginInfo>();

        // 构造函数
        public PluginManagerWindow()
        {
            InitializeComponent();
            LoadPlugins();
        }

        // 加载插件信息
        private void LoadPlugins()
        {
            if (Directory.Exists(PLUGIN_DIRECTORY))
            {
                foreach (string directory in Directory.GetDirectories(PLUGIN_DIRECTORY))
                {
                    string configPath = Path.Combine(directory, "config.xml");
                    if (File.Exists(configPath))
                    {
                        try
                        {
                            XDocument configDoc = XDocument.Load(configPath);
                            var pluginElement = configDoc.Element("plugins");
                            if (pluginElement != null)
                            {
                                string name = Path.GetFileName(directory);
                                string version = pluginElement.Element("version")?.Value ?? "未知";
                                string status = "已安装";
                                string description = pluginElement.Element("description")?.Value ?? "无描述提供";
                                string author = pluginElement.Element("author")?.Value ?? "未知";

                                plugins.Add(new PluginInfo
                                {
                                    Name = name,
                                    Version = version,
                                    Status = status,
                                    Description = description,
                                    Author = author
                                });
                            }
                        }
                        catch (Exception ex)
                        {
                            LogError($"加载插件 {directory} 时出错: {ex.Message}");
                            MessageBox.Show($"加载插件 {directory} 时出错: {ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
                        }
                    }
                }
            }

            PluginListView.ItemsSource = plugins;
        }

        // 打开插件的点击事件处理
        private void OpenPlugin_Click(object sender, RoutedEventArgs e)
        {
            if (PluginListView.SelectedItem is PluginInfo selectedPlugin)
            {
                string pluginPath = Path.Combine(PLUGIN_DIRECTORY, selectedPlugin.Name);
                string configPath = Path.Combine(pluginPath, "config.xml");

                if (File.Exists(configPath))
                {
                    try
                    {
                        XDocument configDoc = XDocument.Load(configPath);
                        var pluginElement = configDoc.Element("plugins");
                        if (pluginElement != null)
                        {
                            string mainDll = pluginElement.Element("main")?.Value;
                            string mainWindowClass = pluginElement.Element("MainWindows")?.Value;

                            if (!string.IsNullOrEmpty(mainDll) && !string.IsNullOrEmpty(mainWindowClass))
                            {
                                string dllPath = Path.Combine(pluginPath, mainDll);
                                Assembly assembly = Assembly.LoadFrom(dllPath);
                                Type type = assembly.GetType(mainWindowClass);

                                if (type != null)
                                {
                                    MethodInfo methodInfo = type.GetMethod("StartPlugin");
                                    if (methodInfo != null)
                                    {
                                        object instance = Activator.CreateInstance(type);
                                        methodInfo.Invoke(instance, null);
                                    }
                                    else
                                    {
                                        HandleError("指定的方法 'StartPlugin' 未找到。");
                                    }
                                }
                                else
                                {
                                    HandleError("指定的类在 DLL 中未找到。");
                                }
                            }
                            else
                            {
                                HandleError("无效的配置文件。");
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        HandleError($"打开插件时出错: {ex.Message}");
                    }
                }
                else
                {
                    HandleError("配置文件未找到。");
                }
            }
            else
            {
                MessageBox.Show("请选择一个插件以打开。", "信息", MessageBoxButton.OK, MessageBoxImage.Information);
            }
        }

        // 安装插件的点击事件处理
        private void InstallPlugin_Click(object sender, RoutedEventArgs e)
        {
            Microsoft.Win32.OpenFileDialog openFileDialog = new Microsoft.Win32.OpenFileDialog
            {
                Filter = "LSP 文件 (*.lsp)|*.lsp"
            };

            if (openFileDialog.ShowDialog() == true)
            {
                string lspFilePath = openFileDialog.FileName;
                string pluginName = Path.GetFileNameWithoutExtension(lspFilePath);
                string extractPath = Path.Combine(PLUGIN_DIRECTORY, pluginName);

                try
                {
                    if (Directory.Exists(extractPath))
                    {
                        throw new Exception($"插件目录 {extractPath} 已存在。");
                    }

                    ZipFile.ExtractToDirectory(lspFilePath, extractPath);
                    MessageBox.Show($"插件 {pluginName} 已成功安装。", "信息", MessageBoxButton.OK, MessageBoxImage.Information);
                    LoadPlugins(); // 刷新列表后安装
                }
                catch (Exception ex)
                {
                    HandleError($"安装插件时出错: {ex.Message}");
                }
            }
        }
        private void UninstallPlugin_Click(object sender, RoutedEventArgs e)
        {
            if (PluginListView.SelectedItem is PluginInfo selectedPlugin)
            {
                string pluginPath = Path.Combine(PLUGIN_DIRECTORY, selectedPlugin.Name);

                try
                {
                    Directory.Delete(pluginPath, true);
                    MessageBox.Show($"插件 {selectedPlugin.Name} 已成功卸载。", "信息", MessageBoxButton.OK, MessageBoxImage.Information);
                    LoadPlugins(); 
                   
                }
                catch (Exception ex)
                {
                    HandleError($"卸载插件时出错: {ex.Message}");
                }
            }
            else
            {
                MessageBox.Show("请选择一个插件以卸载。", "信息", MessageBoxButton.OK, MessageBoxImage.Information);
            }
        }

        // 记录错误日志
        private void LogError(string message)
        {
            if (!Directory.Exists(LOG_DIRECTORY))
            {
                Directory.CreateDirectory(LOG_DIRECTORY);
            }

            string logFilePath = Path.Combine(LOG_DIRECTORY, $"{DateTime.Now:yyyy-MM-dd}.log");
            using (StreamWriter writer = new StreamWriter(logFilePath, true))
            {
                writer.WriteLine($"{DateTime.Now:yyyy-MM-dd HH:mm:ss} - {message}");
            }
        }

        // 统一处理错误信息
        private void HandleError(string message)
        {
            LogError(message);
            MessageBox.Show(message, "错误", MessageBoxButton.OK, MessageBoxImage.Error);
        }

        // 插件信息类
        public class PluginInfo
        {
            public string Name { get; set; }
            public string Version { get; set; }
            public string Status { get; set; }
            public string Description { get; set; }
            public string Author { get; set; }
        }
    }
}